package com.focusai.efairy.ui.adapter.report;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.focusai.efairy.R;
import com.focusai.efairy.model.report.ChildWarnningDataEntity;
import com.focusai.efairy.model.report.WarnningDataType;
import com.focusai.efairy.utils.DateUtils;
import com.focusai.efairy.utils.report.ReportUtils;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import me.drakeet.multitype.ItemViewBinder;

/**
 * Created by luo_guangwen on 2017/8/2.
 */

public class ReportWarnningViewBinder extends ItemViewBinder<WarnningDataType, ReportWarnningViewBinder.ViewHolder> {

    private int[] colors;
    private Context mContext;

    public ReportWarnningViewBinder(int[] colors, Context mContext) {
        this.colors = colors;
        this.mContext = mContext;

    }

    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View root = inflater.inflate(R.layout.item_report_warnning, parent, false);
        ViewHolder viewHolder = new ViewHolder(root);
        initBarChart(viewHolder.barChart);
        return viewHolder;
    }

    @Override
    protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull WarnningDataType item) {
        holder.barChart.setData(refreshBarChart(item, holder.barChart));
        holder.barChart.invalidate();
        holder.barChart.animateY(1500, Easing.EasingOption.EaseInOutQuad);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        BarChart barChart;

        ViewHolder(View itemView) {
            super(itemView);
            barChart = (BarChart) itemView.findViewById(R.id.bar_chart);
        }
    }

    private void initBarChart(BarChart barChart) {

        barChart.setDrawBorders(false); //是否在折线图上添加边框
        barChart.getDescription().setEnabled(false);
//        Description description = new Description();
//        description.setText("2017年06");
//        description.setTextColor(mContext.getResources().getColor(R.color.font_gray));
//        description.setTextSize(mContext.getResources().getDimension(R.dimen.common_font_fs4));
//        barChart.setDescription(description);// 数据描述

//
        barChart.setDrawGridBackground(false); // 是否显示表格颜色
        barChart.setGridBackgroundColor(Color.RED); // 表格的的颜色
        //barChart.setBackgroundColor(Color.BLACK);// 设置整个图标控件的背景
        barChart.setDrawBarShadow(false);//柱状图没有数据的部分是否显示阴影效果
//
//        barChart.setTouchEnabled(false); // 设置是否可以触摸
        barChart.setDragEnabled(false);// 是否可以拖拽
        barChart.setScaleEnabled(false);// 是否可以缩放
        barChart.setPinchZoom(false);//y轴的值是否跟随图表变换缩放;如果禁止，y轴的值会跟随图表变换缩放
        barChart.setDrawValueAboveBar(true);//柱状图上面的数值显示在柱子上面还是柱子里面

        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);
        barChart.setMaxVisibleValueCount(60);

//
        XAxis xAxis = barChart.getXAxis();
        xAxis.setDrawGridLines(false);//是否显示竖直标尺线
//        xAxis.setSpaceMin(11);//设置横坐标显示的间隔
//        barChart.getXAxis().setLabelRotationAngle(20);//设置横坐标倾斜角度
//        barChart.getXAxis().setSpaceBetweenLabels(50);
        xAxis.setDrawLabels(true);//是否显示X轴数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴的位置 默认在上方
        xAxis.setGranularity(1f); // only intervals of 1 day


        YAxis axisRight = barChart.getAxisRight();
        axisRight.setDrawLabels(false);//右侧是否显示Y轴数值
        axisRight.setEnabled(false);//是否显示最右侧竖线
        axisRight.setDrawAxisLine(false);

        YAxis leftAxis = barChart.getAxisLeft();
//        leftAxis.setLabelCount(YLableCount, false);
        leftAxis.setSpaceTop(15f);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setDrawGridLines(false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
//        Legend legend = barChart.getLegend();
//        legend.setPosition(Legend.LegendPosition.ABOVE_CHART_RIGHT);//设置比例图标的位置
//        legend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);//设置比例图标和文字之间的位置方向
//        legend.setTextColor(Color.RED);
//        List<LegendEntry> legendEntries = new ArrayList<>();
//        for (int i = 0; i < XLableCount; i++) {
//            LegendEntry entry = new LegendEntry();
//            entry.label = xLableName[i];
//            entry.formColor = colors[i];
//            legendEntries.add(entry);
//        }
//        legend.setCustom(legendEntries);
//        legend.setExtra(colors,xLableName);
    }


    /**
     * 刷新柱状图
     */
    private BarData refreshBarChart(WarnningDataType warnningDataType, BarChart barChart) {
        List<ChildWarnningDataEntity> list = warnningDataType.getDataEntities();
        if (list == null)
            return new BarData();
        List<BarEntry> yVals = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ChildWarnningDataEntity val = list.get(i);
            yVals.add(new BarEntry(i, val.value, val.name));
        }
        BarDataSet mBarDataSet = new BarDataSet(yVals, "");

        // 如果是0f，那么柱状图之间将紧密无空隙的拼接在一起形成一片。
//        mBarDataSet.setBarBorderWidth(30f);

        // 柱状图柱的颜色
        mBarDataSet.setColors(colors);
        mBarDataSet.setBarShadowColor(Color.rgb(203, 203, 203));
        // 当柱状图某一柱被选中时候的颜色
        mBarDataSet.setHighLightColor(Color.YELLOW);
        List<IBarDataSet> dataSets = new ArrayList<>();
        dataSets.add(mBarDataSet);
        BarData mBarData = new BarData(dataSets);
        mBarData.setValueTextSize(12f);

        //设置X轴
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴的位置 默认在上方
        String[] xLableName = getxLableName(warnningDataType.getDateType(), list);
        if (xLableName != null){
            xAxis.setValueFormatter(new MyIAxisValueFormatter(xLableName));
            xAxis.setLabelCount(warnningDataType.getxCount());
        }else {
            xAxis.setValueFormatter(null);
            xAxis.setLabelCount(xLableName.length);
        }
        return mBarData;
    }

    private String[] getxLableName(int dateType, List<ChildWarnningDataEntity> list) {
        long startDate = System.currentTimeMillis();
        String[] xlableName = null;
        if (list != null && list.size() > 0) {
            startDate = list.get(0).startDataTime;
        }
        try {
            switch (dateType) {
                case ReportUtils.DAY:
                    xlableName = mContext.getResources().getStringArray(R.array.xaxis_bar_day);
                    break;
                case ReportUtils.WEEK:
                    xlableName = mContext.getResources().getStringArray(R.array.xaxis_bar_week);
                    break;
                case ReportUtils.MONDTH:
                    int lenght = DateUtils.getcurMonthDayOfYear(startDate);
                    xlableName = new String[lenght];
                    for (int i = 0; i < lenght; i++) {
                        xlableName[i] = (i + 1) + "";
                    }
                    break;
                case ReportUtils.SESION:
                    Calendar calendar = DateUtils.parseCalendar(startDate);
                    int currentMonth = calendar.get(Calendar.MONTH) + 1;
                    xlableName = new String[3];
                    for (int i = 0; i < 3; i++) {
                        xlableName[i] = (currentMonth + i) + "月";
                    }
                    break;
                case ReportUtils.YEAR:
                    xlableName = new String[12];
                    for (int i = 0; i < 12; i++) {
                        xlableName[i] = (1 + i) + "月";
                    }
                    break;
                case ReportUtils.CUSTOM:
                    xlableName = mContext.getResources().getStringArray(R.array.xaxis_bar_custom);
                    break;
                default:
                    break;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return xlableName;
    }

    class MyIAxisValueFormatter implements IAxisValueFormatter {

        private String[] xLableName;

        public MyIAxisValueFormatter(String[] xLableName) {
            this.xLableName = xLableName;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            if (xLableName != null) {
                int index = (int) value;
                return (index >= 0 && index < xLableName.length) ? xLableName[index] : "";
            } else {
                return "";
            }
        }
    }
}

